package org.fast.framework.helper;

import org.fast.framework.annotation.Controller;
import org.fast.framework.annotation.RequestMapping;
import org.fast.framework.annotation.RequestMapping.RequestMethod;
import org.fast.framework.bean.Handler;
import org.fast.framework.bean.Request;
import org.fast.framework.container.ClassContainer;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 控制器助手类
 */
public final class ControllerHelper {

    // 用于存放请求与处理器的映射关系
    private static final Map<Request, Handler> CONTROLLER_MAP = new HashMap<>();

    static {
        // 获取所有的Controller类
        Set<Class<?>> controllerClassSet = ClassContainer.getClassSetByAnnotation(Controller.class);
        // 遍历这些Controller类
        for (Class<?> controllerClass : controllerClassSet) {
            // 判断控制器是否存在RequestMapping注解
            String prePath = null;
            if (controllerClass.isAnnotationPresent(RequestMapping.class)) {
                prePath = controllerClass.getAnnotation(RequestMapping.class).value();
            }
            // 获取Controller类中定义的方法
            Method[] methods = controllerClass.getDeclaredMethods();
            // 遍历Controller的方法
            for (Method method : methods) {
                // 判断方法是否存在RequestMapping注解
                if (method.isAnnotationPresent(RequestMapping.class)) {
                    RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                    // 从RequestMapping注解中获取url映射规则
                    RequestMethod requestMethod = requestMapping.method();
                    String requestPath;
                    if (prePath == null) {
                        requestPath = requestMapping.value();
                    } else {
                        requestPath = prePath + requestMapping.value();
                    }
                    Request request = new Request(requestMethod, requestPath);
                    Handler handler = new Handler(controllerClass, method);
                    CONTROLLER_MAP.put(request, handler);
                }
            }
        }
    }

    /**
     * 获取 Handler
     *
     * @param requestMethod 请求方法
     * @param requestPath   请求路径
     * @return
     */
    public static Handler getHandler(RequestMethod requestMethod, String requestPath) {
        Request request = new Request(requestMethod, requestPath);
        return CONTROLLER_MAP.get(request);
    }
}
